package com.mtw.bbs.article.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.article.pojo.entity.ArticleIndex;
import com.mtw.bbs.article.pojo.entity.TopicIndex;
import com.mtw.bbs.article.pojo.form.TopicForm;
import com.mtw.bbs.article.pojo.vo.TopicAdminVo;
import com.mtw.bbs.article.service.ArticleIndexService;
import com.mtw.bbs.article.service.TopicIndexService;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.fileAdmin.feign.FileClient;
import com.mtw.bbs.fileAdmin.pojo.vo.FileVo;
import com.mtw.bbs.userAdmin.feign.UserClient;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import com.mtw.bbs.userAdmin.pojo.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 话题接口层
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("admin/topic")
public class AdminTopicController {

    private final UserClient userClient;
    private final FileClient fileClient;
    private final TopicIndexService topicIndexService;
    private final ArticleIndexService articleIndexService;



    /**
     * 搜索话题
     *
     * @param page 当前页
     * @param size 分页大小
     * @param name 话题名称
     * @param type 话题分类
     */
    @GetMapping("/page")
    public Result searchTopic(@RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "name", required = false) String name,
                              @RequestParam(name = "type", required = false) String type) {

        QueryWrapper<TopicIndex> lqw = new QueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), "t.name", name);
        lqw.eq(StringUtils.isNotBlank(type), "t.type_id",type);
        lqw.orderByDesc("t.is_recommend");
        lqw.orderByDesc("t.created_date");

        Page<TopicAdminVo> adminPage = topicIndexService.getAdminPage(page, size, lqw);

        if (CollectionUtil.isNotEmpty(adminPage.getRecords())){
            Set<String> masterSet = adminPage.getRecords().stream().map(TopicAdminVo::getTopicMaster).collect(Collectors.toSet());
            Map<String, UserInfoVo> userMap;
            // 查询题主
            if (!masterSet.isEmpty()){
                Result<List<UserDto>> userResult = userClient.getUserInfoByIds(masterSet.toArray(String[]::new));
                if (userResult.isSuccess() && CollectionUtil.isNotEmpty(userResult.getData())){
                    userMap = userResult.getData().stream().collect(Collectors.toMap(UserDto::getId,UserDto::toSimpleInfoVO));
                } else {
                    userMap = null;
                }
            } else {
                userMap = null;
            }
            adminPage.getRecords().forEach(x -> {
                if (userMap != null) {
                    x.setTopicMasterInfo(userMap.get(x.getTopicMaster()));
                }
            });
        }
        return Result.success(adminPage);
    }


    /**
     * 选择话题
     *
     * @param page 当前页
     * @param size 分页大小
     * @param name 话题名称
     */
    @GetMapping("/select")
    public Result selectTopic(@RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "name", required = false) String name,
                              @RequestParam(name = "type", required = false) String type) {

        LambdaQueryWrapper<TopicIndex> lqw = new LambdaQueryWrapper<>();
        lqw.select(TopicIndex::getId,TopicIndex::getCover,TopicIndex::getName);
        lqw.eq(StringUtils.isNotBlank(type), TopicIndex::getTypeId, type);
        lqw.like(StringUtils.isNotBlank(name), TopicIndex::getName, name);
        lqw.orderByDesc(TopicIndex::getIsRecommend);
        lqw.orderByDesc(TopicIndex::getCreatedDate);

        Page<TopicIndex> indexPage = topicIndexService.page(new Page<>(page, size), lqw);
        Page<TopicAdminVo> voPage = new Page<>(page, size, indexPage.getTotal());
        if (CollectionUtil.isNotEmpty(indexPage.getRecords())){
            String[] fileIds = indexPage.getRecords().stream().map(TopicIndex::getCover).filter(StringUtils::isNotBlank).toArray(String[]::new);
            Result<List<FileVo>> fileUrls = fileClient.getFileUrlByIdArray(fileIds);
            Map<String, String> urlMap;
            if (fileUrls.isSuccess()){
                urlMap = fileUrls.getData().stream().collect(HashMap::new, (map, item) -> map.put(item.getId(), item.getUrl()), HashMap::putAll);
            }else {
                urlMap = new HashMap<>(1);
            }
            List<TopicAdminVo> list = indexPage.getRecords().stream().map(x -> {
                TopicAdminVo vo = new TopicAdminVo();
                vo.setId(x.getId());
                vo.setName(x.getName());
                if (urlMap.get(x.getCover()) != null) {
                    vo.setCover(urlMap.get(x.getCover()));
                }
                return vo;
            }).toList();
            voPage.setRecords(list);

        }
        return Result.success(voPage);
    }




    /**
     * 搜索话题名称
     *
     * @param page 当前页
     * @param size 分页大小
     * @param name 话题名称
     */
    @GetMapping("/selectName")
    public Result selectTopicName(@RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "name", required = false) String name) {

        LambdaQueryWrapper<TopicIndex> lqw = new LambdaQueryWrapper<>();
        lqw.select(TopicIndex::getId,TopicIndex::getCover,TopicIndex::getName);
        lqw.like(StringUtils.isNotBlank(name), TopicIndex::getName, name);
        lqw.orderByDesc(TopicIndex::getIsRecommend);
        lqw.orderByDesc(TopicIndex::getCreatedDate);

        Page<TopicIndex> indexPage = topicIndexService.page(new Page<>(page, size), lqw);
        Page<TopicAdminVo> voPage = new Page<>(page, size, indexPage.getTotal());
        if (CollectionUtil.isNotEmpty(indexPage.getRecords())){
            List<TopicAdminVo> list = indexPage.getRecords().stream().map(x -> {
                TopicAdminVo vo = new TopicAdminVo();
                vo.setId(x.getId());
                vo.setName(x.getName());
                return vo;
            }).toList();
            voPage.setRecords(list);
        }
        return Result.success(voPage);
    }





    /**
     * 新增话题
     *
     * @param form 表单信息
     */
    @PostMapping("/save")
    public Result saveTopic(@RequestBody TopicForm form) {
        boolean saved = topicIndexService.saveTopicByAdmin(form);
        return saved ? Result.success() : Result.fail("保存失败");
    }






    /**
     * 修改话题信息
     *
     * @param form 表单信息
     */
    @PutMapping("/update")
    public Result updateTopic(@RequestBody TopicForm form) {

        boolean updated = topicIndexService.updateByAdmin(form);
        return updated ? Result.success() : Result.fail("保存失败");
    }







    /**
     * 根据id删除话题
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") String id) {
        LambdaQueryWrapper<ArticleIndex> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleIndex::getTopicId,id);
        long count = articleIndexService.count(lqw);
        if (count > 0){
            Result.fail("话题存在关联的文章");
        }
        boolean deleted = topicIndexService.deleteTopicById(id);
        return deleted ? Result.success() : Result.fail("删除失败");
    }



}
